<template>
  <div class="login-container">
    <div class="login-box">
      <h2 style="text-align: center">短信登录</h2>
      <el-form   :model="loginForm" class="login-form" label-width="80px">
        <el-form-item label="手机号码"  >
          <el-input v-model="loginForm.phone" placeholder="请输入手机号码"></el-input>
        </el-form-item>
        <el-form-item label="验证码"  >
          <el-input v-model="loginForm.code" placeholder="请输入短信验证码"></el-input>
          <el-button v-if="!countdown" @click="sendCode" class="code-btn">发送验证码</el-button>
          <el-button v-else class="code-btn" :disabled="countdown" :loading="countdown">
            {{ countdown }}s后重发
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup  >
// 必须放在代码顶层
import { reactive, ref } from 'vue'
import {useRouter} from "vue-router";
import { ElForm, ElFormItem, ElInput, ElButton } from 'element-plus'
import _axios, {dataUrl} from "@/http/request";
import { ElMessage } from 'element-plus'
const route = useRouter();


    const loginForm = ref({
      phone: '',
      code: ''
    })

    const countdown = ref(0)
    let timer = null

    const sendCode = () => {
      // TODO: 发送短信验证码的逻辑
      // 假设发送成功后启动倒计时60秒
      _axios.post(  dataUrl+"/login/sendMessage",{phone:loginForm.value.phone}).then((res)=>{
        console.log(res)
        if (res.data.data.result==0){
          ElMessage({
            message: "验证码下发成功",
            type: 'success',
          })
        }
      })
      countdown.value = 60
      timer = setInterval(() => {
        countdown.value--
        if (countdown.value === 0) {
          clearInterval(timer)
        }
      }, 1000)
    }

    const login = () => {
      // TODO: 短信登录的逻辑
      console.log(123)
      _axios.post(dataUrl+"/login/loginuser",loginForm.value ).then((res)=>{
        console.log(res)
        if (res.data.code==200){
          ElMessage({
            message:res.data.message,
            type: 'success',
          })
          route.push("/main")
        }else {
          ElMessage({
            message:res.data.message,
            type: 'warning',
          })
        }
      })
    }


</script>

<style scoped>
.login-container {
  background-image: url("https://tgg.cloudtgg.com/cloud/202304220331940.jpg");
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.login-box {
  width: 400px;
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.login-form {
  margin-top: 20px;
}
.code-btn {
  float: right;
  margin-top: 5px;
}
</style>
